package com.vote.www.core.quartz;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;

import com.vote.www.utils.LocalDateTime;

/**
 * 会话
 * 
 * @author 汤伟杰
 *
 */
@Controller
public class AppMap {

	private static Map<String, Map<String, Object>> vcode;// 验证码缓存

	
	/**
	 * 设置验证码缓存
	 * 
	 * @param vali
	 * @param tk
	 */
	public static void setVcode(String vali, String tk) {
		if (StringUtils.isNotBlank(tk)) {
			if (vcode == null) {
				vcode = new HashMap<String, Map<String, Object>>();
			}
			if (vcode.get(tk) != null) {
				vcode.remove(tk);
			}
			Map<String, Object> object = new HashMap<String, Object>();
			object.put("name", vali);
			object.put("creattime", System.currentTimeMillis());
			vcode.put(tk, object);
		}

	}


	public static Map<String, Map<String, Object>> getVcode(){
		if(vcode==null){
			vcode= new HashMap<String, Map<String,Object>>();
		}
		return vcode;
	}
	/**
	 * 获取验证码
	 * 
	 * @param tk
	 * @return
	 */
	public static String getVcode(String tk) {
		if(tk==null){
			return null;
		}
		if (getVcode().get(tk) != null) {
			return (String) getVcode().get(tk).get("name");
		}
		return null;
	}



	/**
	 * 获取验证码map
	 * 
	 * @return
	 */
	public static Map<String, Map<String, Object>> getVcodeMap() {
		return getVcode();
	}

	public static void removeVcode(String tk) {
		if (getVcode().get(tk) != null) {
			vcode.remove(tk);
		}
	}

	/**
	 * 检查并删除验证码
	 * 
	 * @param date
	 * @return
	 */
	public static boolean checkOutOfDateVcode(Date date) {
		if (vcode != null) {
			for (Entry<String, Map<String, Object>> entry : vcode.entrySet()) {
				Long lg = 5*60 * 1000 - (LocalDateTime.getDateTime(date) - (Long) entry.getValue()
						.get("creattime"));
				if (lg < 0) {
					System.out.println("删除vcode，tk:" + entry.getKey()
							+ ";value:" + entry.getValue());
					vcode.remove(entry.getKey());

				}

			}
		}

		return true;
	}





}
